package com.core.config.filter;

import com.alibaba.fastjson.JSON;
import com.core.system.utils.SecurityUser;
import com.redis.RedisUtil;
import com.utility.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * 重复提交过滤器
 * @author Huawei
 * @date 2023-10-23 15:36
 */

@WebFilter(filterName = "submitAgainFilter", urlPatterns = "/*")
@Order(value = 2)
@Slf4j
public class SubmitAgainFilter implements Filter {
    @Resource
    public RedisUtil redisUtil;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        Long userId = SecurityUser.getUserId();
        HttpServletRequest req =  (HttpServletRequest)request;
        String submitInfoKey = request.getLocalAddr()+":"+request.getServerPort()+req.getRequestURI()+":"+userId;
        if (Objects.nonNull(redisUtil.get(submitInfoKey))){
            HttpServletResponse resp = (HttpServletResponse)response;
           // 返回hhtp 500状态码 返回类型utf-8 返回描述 重复提交
            resp.setContentType("application/json;charset=utf-8");
            resp.setStatus(500);
            resp.getWriter().write(JSON.toJSONString(Result.returnCode(-1,"重复提交")));
            resp.getWriter().flush();
           return;
        }
        //自动过期时间60秒，以免出现请求卡死情况
        redisUtil.set(submitInfoKey,Boolean.TRUE,60);
        chain.doFilter(request, response);
    }

}
